<?php

class System_Models_List extends Zend_Db_Table_Abstract {

    protected $_name = "list";
    protected $_primary = "ListID";
    protected $_primary_name;
    public function __construct()
    {
        parent::__construct();
        $this->_primary_name = $this->_primary;
    }
    public function getAllList($params) {

        $pagenum = $params['pagenum'];
        $pagesize = $params['pagesize'];
        $start = $pagenum * $pagesize;
        // Filter
        $where = '1=1';
        if (isset($params['filterscount']))
        {
            $filterscount = $params['filterscount'];
            
            if ($filterscount > 0)
            {
                $where .= " And (";
                $tmpdatafield = "";
                $tmpfilteroperator = "";
                for ($i=0; $i < $filterscount; $i++)
                {
                    $filtervalue = $params["filtervalue" . $i];
                    $filtercondition = $params["filtercondition" . $i];
                    $filterdatafield = $params["filterdatafield" . $i];
                    $filteroperator = $params["filteroperator" . $i];
                    if ($filterdatafield =='ListtypeName') {
                        $filterdatafield = 'ListtypeID';
                        $arr = explode('##', $filtervalue);
                        $filtervalue = $arr[1];
                    }
                    
                    if ($tmpdatafield == "")
                    {
                        $tmpdatafield = $filterdatafield;           
                    }
                    else if ($tmpdatafield <> $filterdatafield)
                    {
                        $where .= ")AND(";
                    }
                    else if ($tmpdatafield == $filterdatafield)
                    {
                        if ($tmpfilteroperator == 0)
                        {
                            $where .= " AND ";
                        }
                        else $where .= " OR ";  
                    }
                    $filterdatafield = 'A.'.$filterdatafield;
                    $where .= Clound_Public::getInstance()->getClauseByFilter($filtercondition, $filterdatafield, $filtervalue);
                                    
                    if ($i == $filterscount - 1)
                    {
                        $where .= ")";
                    }
                    
                    $tmpfilteroperator = $filteroperator;
                    $tmpdatafield = $filterdatafield;           
                }  
            }
        }
        // Sort
        $orders =' A.Orders ASC';
        if (isset($params['sortdatafield'])) {
            $sortfield = $params['sortdatafield'];
            if ($sortfield =='ListtypeName') $sortfield = 'ListtypeID';
            $sortfield = "A.".$sortfield;
            $sortorder = $params['sortorder'];
            if ($sortorder != '') {
                if ($sortorder == "desc") {
                    $orders = " " . $sortfield . " DESC";
                } else if ($sortorder == "asc") {
                    $orders = " " . $sortfield . " ASC";
                }
            }
        }

        // Lay tong
        $query = $this->getAdapter()->select()
                        ->from(array('A' => $this->_name),array())
                        ->join(array('B' => 'listtype'),'A.ListtypeID = B.ListtypeID',array())
                        ->columns(array('total' => new Zend_Db_Expr('COUNT(*)')))
                        ->where($where);

        try {
            $rows = $this->getAdapter()->fetchRow($query);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        $total_rows = $rows['total'];
        // Lay du lieu
        $query = $this->getAdapter()->select()
                        ->from(array('A' => $this->_name))
                        ->join(array('B' => 'listtype'),'A.ListtypeID = B.ListtypeID',array('B.Name As ListtypeName'))
                        ->where($where)
                        ->order($orders)
                        ->limit($pagesize, $start);
        try {
            $rows = $this->getAdapter()->fetchAll($query);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        $data[] = array(
            'TotalRows' => $total_rows,
            'Rows' => $rows
        );

        return $data;
    }

    public function selectRow($ListID,$ListtypeID){
        if($ListID){
            $query = $this->select()->from($this)->where('ListID = ?', $ListID);
            try {
                $rows = $this->getAdapter()->fetchRow($query);
            } catch (Exception $e) {
                echo $e->getMessage();
            }
        }else{
            $query = $this->select()->from($this, '')
                        ->columns(array('Orders' => new Zend_Db_Expr('MAX(Orders)')))
                        ->where('ListtypeID = ?', $ListtypeID);
            $orders = $this->getAdapter()->fetchRow($query);
            $rows = array('ListID'=>''
                            ,'Code'=>''
                            ,'Name'=>''
                            ,'Orders'=>$orders['Orders']+1
                            ,'Status'=>'1'
                            ,'ListtypeID'=>$ListtypeID
                        );
        }
        return $rows;
    }
    public function deleteRows($listId){
        $aListID = explode(',', $listId);
        try {
            $where = $this->getAdapter()->quoteInto("$this->_primary_name IN (?)", $aListID);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        return $this->delete($where);
    }
    
    public function isValid($data){
        $where = " Where ".$this->getAdapter()->quoteInto("$this->_primary_name <> ?", $data[$this->_primary_name])
                .$this->getAdapter()->quoteInto(" And Code = ?",$data['Code']);
        try {
            $rows = $this->getAdapter()->fetchRow("SELECT COUNT(*) as total FROM $this->_name ".$where);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        if($rows['total']){
            return false;
        }else{
            return true;
        }
        return $rows['total'];
    }

    public function reOrder($iListID,$iListtypeID,$iOrder){
         $where = " Where ".$this->getAdapter()->quoteInto("$this->_primary_name <> ?", $iListID)
                    .$this->getAdapter()->quoteInto(" And ListtypeID = ?",$iListtypeID)
                    .$this->getAdapter()->quoteInto(" And Orders >= ?",$iOrder);
        try {
            $rows = $this->getAdapter()->fetchAll("SELECT $this->_primary_name,Orders FROM $this->_name ".$where." Order by Orders");
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        if($rows){
            foreach ($rows as $key => $value) {
                $id = $value[$this->_primary_name];
                try {
                    $this->update(array('Orders'=> $iOrder+1+$key),"$this->_primary_name = $id");
                } catch (Exception $e) {
                    echo $e->getMessage();
                }
            }
        }
        return $rows;

    }    

}
